package top.aigoo.project01.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.aigoo.project01.cache.JedisUtil;
import top.aigoo.project01.entity.Area;
import top.aigoo.project01.mapper.AreaMapper;
import top.aigoo.project01.service.AreaService;
import top.aigoo.project01.service.CacheService;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 区域
 *
 * @Author: Mr.OYSHUO.欧阳大叔  mail:1642302522@qq.com
 * @Version 1.0.0
 * @version 2.0  引入了redis
 * @Date: 2021/8/6 0:30
 */
@Service
public class AreaServiceImpl implements AreaService {
    private static Logger logger = LoggerFactory.getLogger(AreaServiceImpl.class);
    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private JedisUtil.Keys jedisKeys;

    @Autowired
    private JedisUtil.Strings jedisStrings;

    @Autowired
    private CacheService cacheService;

    @Override
    @Transactional
    public List<Area> getAreaList() {
        //定义redis的key
        String key = AREALISTKEY;
        //定义接收对象
        List<Area> areaList = null;
        //定义jackson的数据转换操作类
        ObjectMapper mapper = new ObjectMapper();
        //判断key是否存在
        if (!jedisKeys.exists(key)) {//1.不存在，就从数据库里面取出相应数据
            areaList = areaMapper.queryArea();
            String jsonString = null;
            try {
                //将相关的实体类集合转换成string,存入到redis里面对应的key中
                jsonString = mapper.writeValueAsString(areaList);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                throw new RuntimeException(e.getMessage());
            }
            jedisStrings.set(key, jsonString);  //将键值对设置到redis缓存中
        } else {//2.存在，从缓存取出相应数据
            String jsonString = jedisStrings.get(key);
            //获取类型的创建工厂
            JavaType javaType = mapper.getTypeFactory().constructParametricType(ArrayList.class, Area.class);
            try {
                areaList = mapper.readValue(jsonString, javaType);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
                throw new RuntimeException(e.getMessage());
            }
        }
        return areaList;
    }
}
